<?php
/**
 * Create by PhpStorm
 * User: mozongyou
 * Date: 2021/8/14
 * Time: 6:49 下午
 */
/**
 *
 * ${PARAM_DOC}
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 * @author mozongyou
 * @date 2021-08-14 6:49 下午
 */
declare(strict_types=1);

namespace App\Controller;

use App\Service\WebSocket\FdService;
use App\Service\WebSocket\MessageService;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Swoole\Http\Request;
use Swoole\Websocket\Frame;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{

    public function onMessage($server, Frame $frame): void
    {
        MessageService::getInstance()->processor($frame->fd, $frame->data);
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        FdService::getInstance()->clearData($fd);
    }

    public function onOpen($server, Request $request): void
    {
        $fdService = FdService::getInstance();
        $fdService->putFdList($request->fd);
        $fdService->setHeartbeat($request->fd);
        $server->push($request->fd, json_encode([
            'code' => 1,
            'msg' => '连接成功'
        ], JSON_UNESCAPED_UNICODE));
    }
}